package main

import (
	"fmt"
	"log"

	"github.com/dsoprea/go-exif/exif"
)

func main() {
	// 图片路径
	filename := "path/to/your/image.jpg"

	// 读取图片文件
	x, err := exif.Open(filename)
	if err != nil {
		log.Fatalf("Failed to open file: %v", err)
	}
	defer x.Close()

	// 解析 EXIF 数据
	sections, err := x.Read()
	if err != nil {
		log.Fatalf("Failed to read EXIF data: %v", err)
	}

	// 输出 EXIF 信息
	for _, section := range sections {
		for _, tag := range section.Tags() {
			fmt.Printf("%s: %v\n", tag.Tag(), tag.Value())
		}
	}

	// 提取 GPS 信息
	gpsSection, ok := sections["GPS"]
	if !ok {
		fmt.Println("No GPS info found.")
		return
	}

	// GPS 纬度
	gpsLatitudeTag, _ := gpsSection.Get(exif.GPSTagLatitude)
	gpsLatitudeRefTag, _ := gpsSection.Get(exif.GPSTagLatitudeRef)

	// GPS 经度
	gpsLongitudeTag, _ := gpsSection.Get(exif.GPSTagLongitude)
	gpsLongitudeRefTag, _ := gpsSection.Get(exif.GPSTagLongitudeRef)

	var latitude, longitude string
	var latValue, longValue []string

	if gpsLatitudeTag != nil {
		latValue = gpsLatitudeTag.Values().GetStringArray()
		latitude = convertDMS(latValue, gpsLatitudeRefTag.Value().GetString())
	}

	if gpsLongitudeTag != nil {
		longValue = gpsLongitudeTag.Values().GetStringArray()
		longitude = convertDMS(longValue, gpsLongitudeRefTag.Value().GetString())
	}

	fmt.Printf("GPS Latitude: %s\n", latitude)
	fmt.Printf("GPS Longitude: %s\n", longitude)
}

func convertDMS(values []string, ref string) string {
	var degrees, minutes, seconds float64
	fmt.Sscanf(values[0], "%f/%f", &degrees, &degrees)
	fmt.Sscanf(values[1], "%f/%f", &minutes, &minutes)
	fmt.Sscanf(values[2], "%f/%f", &seconds, &seconds)

	decimalDegrees := degrees + minutes/60 + seconds/3600
	if ref == "S" || ref == "W" {
		decimalDegrees = -decimalDegrees
	}

	return fmt.Sprintf("%f", decimalDegrees)
}
